<template>
    <div class="login-container">
        <el-card class="login-card">
            <template #header>
                <div class="card-header">
                    <h2>管理后台登录</h2>
                </div>
            </template>
            <div class="login-form">
                <div class="verification-code">
                    <h3>验证码：{{ verificationCode }}</h3>
                    <p>请将此验证码发送给机器人 <a :href="botLink" target="_blank">@{{ botUsername }}</a></p>
                </div>
                <el-button type="primary" @click="refreshCode">刷新验证码</el-button>

                <div class="telegram-info" v-if="showTelegramInput">
                    <el-input v-model="telegramInfo" type="textarea" :rows="4" placeholder="请粘贴机器人发送的用户信息"
                        @input="handleTelegramInfoInput" />
                    <div class="status-message" v-if="statusMessage">
                        <el-alert :title="statusMessage" :type="statusType" :closable="false" show-icon />
                    </div>
                </div>
            </div>
        </el-card>
    </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { setToken } from '../utils/auth'
import request from '../utils/request'

export default {
    name: 'Login',
    setup() {
        const router = useRouter()
        const verificationCode = ref('')
        const botUsername = ref('')
        const botLink = ref('')
        const showTelegramInput = ref(false)
        const telegramInfo = ref('')
        const statusMessage = ref('')
        const statusType = ref('info')
        let pollInterval = null

        // 处理Telegram用户信息输入
        const handleTelegramInfoInput = (value) => {
            try {
                const userInfo = JSON.parse(value)
                if (userInfo.id && userInfo.username) {
                    localStorage.setItem('telegramUser', JSON.stringify(userInfo))
                    statusMessage.value = '用户信息已保存，正在验证...'
                    statusType.value = 'success'
                    startPolling()
                }
            } catch (error) {
                statusMessage.value = '请输入有效的用户信息'
                statusType.value = 'error'
            }
        }

        // 生成验证码
        const generateCode = async () => {
            try {
                const res = await request.post('/api/auth/generate-code')
                verificationCode.value = res.data.code
                botUsername.value = res.data.botUsername
                botLink.value = `https://t.me/${botUsername.value}`
                showTelegramInput.value = true
                statusMessage.value = '请将验证码发送给机器人，然后将机器人返回的用户信息粘贴到下方输入框'
                statusType.value = 'info'
                telegramInfo.value = ''
            } catch (error) {
                ElMessage.error('获取验证码失败')
            }
        }

        // 开始轮询检查验证状态
        const startPolling = () => {
            // 清除之前的轮询
            if (pollInterval) {
                clearInterval(pollInterval)
            }

            pollInterval = setInterval(async () => {
                try {
                    // 从localStorage获取Telegram用户信息
                    const telegramUser = JSON.parse(localStorage.getItem('telegramUser') || '{}')

                    const res = await request.post('/api/auth/verify-code', {
                        code: verificationCode.value,
                        telegramId: telegramUser.id,
                        username: telegramUser.username,
                        firstName: telegramUser.first_name,
                        lastName: telegramUser.last_name
                    })

                    if (res.data.verified) {
                        clearInterval(pollInterval)
                        setToken(res.data.token)
                        ElMessage.success('登录成功')
                        router.push('/admin')
                    }
                } catch (error) {
                    console.error('验证失败:', error)
                    statusMessage.value = '验证失败，请检查用户信息是否正确'
                    statusType.value = 'error'
                }
            }, 2000) // 每2秒检查一次

            // 5分钟后停止轮询
            setTimeout(() => {
                if (pollInterval) {
                    clearInterval(pollInterval)
                    statusMessage.value = '验证超时，请重新获取验证码'
                    statusType.value = 'warning'
                }
            }, 5 * 60 * 1000)
        }

        const refreshCode = () => {
            generateCode()
        }

        onMounted(() => {
            generateCode()
        })

        return {
            verificationCode,
            botUsername,
            botLink,
            showTelegramInput,
            telegramInfo,
            statusMessage,
            statusType,
            handleTelegramInfoInput,
            refreshCode
        }
    }
}
</script>

<style scoped>
.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f5f7fa;
}

.login-card {
    width: 400px;
}

.card-header {
    text-align: center;
}

.login-form {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
}

.verification-code {
    text-align: center;
    margin-bottom: 20px;
}

.verification-code h3 {
    font-size: 24px;
    color: #409EFF;
    margin-bottom: 10px;
}

.telegram-info {
    width: 100%;
    margin-top: 20px;
}

.status-message {
    margin-top: 10px;
}
</style>